﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ShenNius.Repository;
using ShenNius.Sys.API.Controllers;
using ShenNius.Sys.API.Dtos.Common;
using ShenNius.Sys.API.Infrastructure.Configs;
using ShenNius.Wechat.API.Domain.Entity;
using ShenNius.Wechat.API.Dtos.Input;
using ShenNius.Wechat.API.Infrastructure.Common;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
/*************************************
* 类名：WeixinController
* 作者：realyrare
* 邮箱：mahonggang8888@126.com
* 时间：2021/6/9 16:56:10
*┌───────────────────────────────────┐　    
*│　   版权所有：神牛软件　　　　	     │
*└───────────────────────────────────┘
**************************************/

namespace ShenNius.Wechat.API.Controllers
{
    public class MaterialController : ApiTenantBaseController<Material, DetailTenantQuery, DeletesTenantInput, KeyListTenantQuery, Material, Material>
    {
        private readonly IBaseRepository<Material> _repository;
        private readonly WxBaseService _wxBaseService;
        private readonly HttpHelper _httpHelper;

        public MaterialController(IBaseRepository<Material> repository, IMapper mapper, WxBaseService wxBaseService, HttpHelper httpHelper) : base(repository, mapper)
        {
            _repository = repository;
            _wxBaseService = wxBaseService;
            _httpHelper = httpHelper;
        }

        /// <summary>
        /// 根据公众号获得素材
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetMaterialByWxId([FromBody] DetailTenantQuery query)
        {
            var token = await _wxBaseService.GetAccessTokenAsync(query.Id);
            var list = _wxBaseService.GetMediaList(token);
            return new ApiResult(list);
        }

        ///// <summary>
        ///// 同步到微信公众号，没有保存
        ///// </summary>
        ///// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> PushMaterial([FromBody] DetailTenantQuery query)
        {
            //根据公众号查询配置
            var token = await _wxBaseService.GetAccessTokenAsync(query.Id);
            //提交素材的Url
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}", token);
            //定义变量只接受同步成功的素材
            var asynOkList = new List<Material>();
            //定义标识，是否有素材没有上传成功
            bool isUploadOk = true, asynOk = true;
            //根据公众号查询所有
            var list = await _repository.GetListAsync(m => m.WechatId == query.Id && m.Position == 1, m => m.CreateTime, false);
            string directorySeparatorChar = Path.DirectorySeparatorChar.ToString();
            if (list.Count > 0)
            {
                //到微信服务端获得thumb_media_id
                foreach (var item in list)
                {
                    var articleList = new List<MeterArticle>();
                    item.Position = 2;
                    if (!string.IsNullOrEmpty(item.TestJson))
                    {
                        var resList = JsonConvert.DeserializeObject<List<Material>>(item.TestJson);
                        foreach (var row in resList)
                        {
                            var fileExt = Path.GetExtension(row.Img);
                            var mapPath = Path.Combine("wwwroot", $"/wwwroot{row.Img}".TrimStart('~', '/').Replace("/", directorySeparatorChar));
                            var resultJson = _wxBaseService.UploadFile(token, mapPath, fileExt);
                            if (resultJson.Code == 200)
                            {
                                articleList.Add(new MeterArticle()
                                {
                                    Title = row.Title,
                                    thumbMediaId = resultJson.MediaId,
                                    Author = row.Author,
                                    Digest = row.Summary,
                                    Content = row.Content,
                                    ContentSourceUrl = row.Link
                                });
                            }
                            else
                            {
                                isUploadOk = false;
                            }
                        }
                    }
                    //开始发送到微信
                    var postStr = JsonConvert.SerializeObject(new { articles = articleList });
                    string resMewsJson = await _httpHelper.PostAsync<string>(url, postStr);
                    if (resMewsJson.Contains("errcode"))
                    {
                        asynOk = false;
                    }
                    else
                    {
                        asynOkList.Add(item);
                    }
                }
            }
            if (!isUploadOk)
            {
                return new ApiResult("上传素材失败~");
            }
            if (!asynOk)
            {
                return new ApiResult("同步素材失败~");
            }
            //只修改同步成功的素材
            if (asynOkList.Count > 0)
            {
                await _repository.UpdateAsync(list);
            }
            return new ApiResult();
        }



        /// <summary>
        /// 素材同步到公众号
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> PushMaterial([FromBody] Material input)
        {
            var token = await _wxBaseService.GetAccessTokenAsync(input.Id);
            int flag = 0;
            if (input.Id == 0)
            {
                var model = Material.Create(input);
                flag = await _repository.AddAsync(model);
            }
            else
            {
                flag = await _repository.UpdateAsync(input);
            }
            var articleList = new List<MeterArticle>();
            //定义标识，是否有素材没有上传成功
            var isUploadOk = true;
            //根据公众号查询所有
            var list = await _repository.GetListAsync(m => m.WechatId == input.WechatId && m.Position == 1, m => m.CreateTime, false);
            string directorySeparatorChar = Path.DirectorySeparatorChar.ToString();
            if (list.Count > 0)
            {
                //到微信服务端获得thumb_media_id
                foreach (var item in list)
                {
                    item.Position = 2;
                    if (!string.IsNullOrEmpty(item.TestJson))
                    {
                        var resList = JsonConvert.DeserializeObject<List<Material>>(item.TestJson);
                        foreach (var row in resList)
                        {
                            var fileExt = Path.GetExtension(row.Img);
                            var path = row.Img;
                            if (!path.ToLower().StartsWith("http") && !path.ToLower().StartsWith("https"))
                            {
                                path = Path.Combine("wwwroot", $"/wwwroot{row.Img}".TrimStart('~', '/').Replace("/", directorySeparatorChar));
                            }
                            var resultJson = _wxBaseService.UploadFile(token, path, fileExt);
                            if (resultJson.Code == 200)
                            {
                                articleList.Add(new MeterArticle()
                                {
                                    Title = row.Title,
                                    thumbMediaId = resultJson.MediaId,
                                    Author = row.Author,
                                    Digest = row.Summary,
                                    Content = row.Content,
                                    ContentSourceUrl = row.Link
                                });
                            }
                            else
                            {
                                isUploadOk = false;
                            }
                        }
                    }
                }
            }
            if (!isUploadOk)
            {
                return new ApiResult("同步素材失败~");
            }
            var postStr = JsonConvert.SerializeObject(new { articles = articleList });
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}", token);
            string resMewsJson = await _httpHelper.PostAsync<string>(url, postStr);
            if (resMewsJson.Contains("errcode"))
            {
                return new ApiResult("上传图文失败~");
            }
            //修改状态
            await _repository.UpdateAsync(list);
            return new ApiResult();
        }
    }
}